package cn.codeforfun.mq.topic;

import cn.codeforfun.jfinalplugin.activemq.core.JFinalTopic;

import javax.jms.JMSException;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * Created by Administrator on 2016/3/27.
 */
public class ActiveMqTopic extends JFinalTopic {

//    Message message;
    MessageListener listener;

    public ActiveMqTopic(String topicName,MessageListener listener) {
        mq(topicName).listener(listener);
    }

    public ActiveMqTopic(String topicName) {
        mq(topicName).listener(topicName);//topicName作为listenerName
    }

    public ActiveMqTopic() {
        //提供空对象用于链式
    }

    public ActiveMqTopic mq(String topicName){
        init(topicName);
        return this;
    }

    public ActiveMqTopic listener(MessageListener listener) {
        this.listener = listener;
        addListener(listener);
        return this;
    }

    public ActiveMqTopic listener (String listenerName){
        this.listener = msg -> {
            try {
                System.out.println(listenerName+"收到消息:" +
                        ((TextMessage) msg).getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        };
        addListener(listener);
        return this;
    }

    public void run() {
        listenerHashMap();
        try {
            getConsumer().setMessageListener(
                    listener(getTopicName()).listener);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}
